package org.jctc.els.modules.biz.service.user.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.codehaus.janino.IClass;
import org.jctc.els.common.constant.MyConstant;
import org.jctc.els.common.utils.PassWordUtil;
import org.jctc.els.modules.biz.entity.user.User;
import org.jctc.els.modules.biz.mapper.user.UserMapper;
import org.jctc.els.modules.biz.service.user.IUserService;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lyh
 * @since 2021-02-26
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public IPage<User> selectUserPage(IPage<User> page, String account, String status,Long deptId) {
        return page.setRecords(userMapper.selectUserPage(page,account,status,deptId));
    }

    @Override
    public IPage<User> selectDpetUserPage(IPage<User> page, String account, String status, Long deptId) {
        return page.setRecords(userMapper.selectDeptUserPage(page,account,status,deptId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(User user) {
        if (Func.isNotEmpty(user.getPassword())) {
            user.setPassword(DigestUtil.encrypt(user.getPassword()));
        }
        Integer userCount = userMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getAccount, user.getAccount()));
        if (userCount > 0 && Func.isEmpty(user.getId())) {
            throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
        }
        BladeUser loginUser = AuthUtil.getUser();
        user.setCreatedTime(DateUtil.now());
        user.setCreatedBy(loginUser.getUserId());
        user.setStatus(1);
        user.setSalt("1");
        user.setAvatar("1");
        if (ObjectUtil.isEmpty(user.getDeptId())) {
            user.setDeptId("1123598816738675201");
        }
        user.setOauthId("1123598816738675201");
        user.setPostId("1123598816738675201");
        return save(user);

    }

    @Override
    public boolean remove(Long id) {
        boolean result = userMapper.deleteById(id) > 0;
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
        if (Func.isEmpty(user.getPassword())) {
            user.setPassword(DigestUtil.encrypt(user.getPassword()));
        }
        Integer userCount = baseMapper.selectCount(
                Wrappers.<User>query().lambda()
                        .eq(User::getAccount, user.getAccount())
                        .notIn(User::getId, user.getId())
        );
        if (userCount > 0) {
            throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
        }
        return updateUserInfo(user);
    }

    @Override
    public boolean updateUserInfo(User user) {
        BladeUser loginUser = AuthUtil.getUser();
        user.setUpdatedBy(loginUser.getUserId());
        user.setUpdatedTime(DateUtil.now());
        return baseMapper.updateById(user) > 0;
    }

    @Override
    public boolean resetPassword(Long id) {
        User userExpand = userMapper.selectById(id);
        String account = userExpand.getAccount();
        String password = "";
        Map<String, String> map = null;
        String salt = "";
        if (account != null) {
            //重置密码为账号后8位
            map = PassWordUtil.generate(account.substring(account.length() - 8));
        } else {
            map = PassWordUtil.generate(MyConstant.DEFAULT_PASSWORD);
        }
        password = map.get("password");
        salt = map.get("salt");
        User user = new User();
        user.setId(id);
        user.setSalt(salt);
        user.setPassword(password);
        boolean res = userMapper.updateById(user) > 0;

        return res;
    }

	@Override
	public boolean enable(Long userId) {
		User user = new User();
		user.setId(userId);
		user.setStatus(MyConstant.STATUS_ENABLED);
		boolean result = userMapper.updateById(user) > 0;
		return result;
	}

	@Override
	public boolean disabled(Long userId) {
		User user = new User();
		user.setId(userId);
		user.setStatus(MyConstant.STATUS_DISABLED);
		boolean result = userMapper.updateById(user) > 0;
		return result;
	}

    @Override
    public IPage<User> selectExpertsPage(IPage<User> page, String account, String status) {
        return page.setRecords(userMapper.selectExpertsPage(page,account,status));
    }

    @Override
    public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
        User user = getById(userId);
        if (!newPassword.equals(newPassword1)) {
            throw new ServiceException("请输入正确的确认密码!");
        }
        if (!user.getPassword().equals(DigestUtil.hex(oldPassword))) {
            throw new ServiceException("原密码不正确!");
        }
        return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.hex(newPassword)).eq(User::getId, userId));
    }

    @Override
    public IPage<User> selectSpecialPage(IPage<User> page, String account, String status,String deptId) {
        return page.setRecords(userMapper.selectSpecialPage(page,account,status,deptId));
    }

    @Override
    public IPage<User> selectExpertListByPage(IPage<User> page) {
        return page.setRecords(userMapper.selectExpertListByPage(page));
    }

    @Override
    public IPage<User> selectBoundExpertsListByPage(IPage<User> page, String teamId) {
        return page.setRecords(userMapper.selectBoundExpertsListByPage(page,teamId));
    }

}
